package glassline;

import glassline.interfaces.Conveyor;
import glassline.interfaces.Sensor;
import agent.*;
import transducer.*;

public class SensorAgent extends Agent implements TReceiver, Sensor
{
	/*		Data
	 * 
	 */
	private Transducer t;
	private Boolean on;
	private Boolean glassDetected;
	private Conveyor convey;// coneveyor sensor is on
	private int id;//id to distnguish
	private String name;
	
	/*Constructor
	 * sets all data ,registers with transducer
	 */
	public SensorAgent(Conveyor conveys, Transducer trans, int ids)
	{
		convey = conveys;
		t = trans;
		on = true;
		glassDetected = false;
		t.register(this, TChannel.SENSORS);
		id = ids;
		name = "Sensor " + id;
		
	}
	/* (non-Javadoc)
	 * @see glassline.Sensor#eventFired(transducer.TChannel, transducer.TEvent, java.lang.Object[])
	 * 
	 */
	@Override
	public void eventFired(TChannel channel, TEvent event, Object[] args)
	{
		if(channel == TChannel.SENSORS)
		{
			if(event == TEvent.SENSED_GLASS)
			{
				if(id == (Integer) args[0])
				{
					glassDetected = true;
					print("Sensor " + id + " sensed glass!");
					stateChanged();	
				}
			}
		}
	}
	/* turns sensor on or off
	 * 
	 */
	public void turnOnOff()
	{
		if(on == true)
		{
			on = false;
		}
		else
		{
			on = true;
		}
	}
	
	@Override
	/*Scheduler
	 * (non-Javadoc)
	 * @see agent.Agent#pickAndExecuteAnAction()
	 * 
	 * if glass is detected then send a message to the conveyor
	 */
	public boolean pickAndExecuteAnAction() {
		if(glassDetected)
		{
			doSensedGlass();
		}
		return false;
	}
	/* sends a message to the conveyor when glass is detected
	 * 
	 */
	public void doSensedGlass()
	{
		convey.msgSensedGlass(this);
		glassDetected = false;
	}
	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#toString()
	 * return name
	 */
	public String toString()
	{
		return name;
	}
	
}
